import time
from block import Block
import random
import datetime
import json
import threading
from p2p_client import broadcast
from block_chain import get_block_chain, calculate_hash, bits, bits_target, add_block, generate_next_block

# 挖矿信息列表
miner_info = []


def proof_of_work(data, nonce):
    """
    挖矿
    :param nonce: 计数器
    :param data: 区块数据
    :return:
    """

    # 新区块信息
    new_block = generate_next_block(data, nonce)
    # 区块hash
    # new_block.data_hash = calculate_hash(new_block)
    # 校验hash
    if int("0x" + new_block.data_hash, 16) < bits_target:
        # 添加区块，回调函数广播到区块链
        add_block(new_block, to_broadcast)

        return True
    else:
        return False


class Miner:
    # 线程结束标志
    thread_flag = False

    # 挖矿线程
    miner_thread = threading.Thread()


def end_miner():
    """
    终止挖矿线程
    :return: void
    """
    Miner.thread_flag = False


def start_miner():
    """
    开始挖矿
    :return: void
    """
    _nonce = 0
    start_time = datetime.datetime.now()
    while Miner.thread_flag:
        _nonce += 1
        # pof工作量证明
        flag = proof_of_work("New_Block_" + str(random.randint(0, 10)) + str(_nonce), _nonce)
        # 返回非False，挖矿成功
        if flag:
            _nonce = 0
            end_time = datetime.datetime.now()
            print("挖矿花费时间：", (end_time - start_time).seconds)
            # 休眠2秒
            time.sleep(2)
            # 重新计时
            start_time = datetime.datetime.now()


def to_broadcast(block_data):
    """
    添加区块回调函数，添加成功时进行广播
    :param block_data:
    :return: void
    """

    if block_data:
        # 添加挖矿信息
        miner_info.append(block_data.get_block_info())
        # 挖矿成功，进行广播
        broadcast(block_data)
